<template>
  <!--弹出窗-->
  <modal ref="modal_1"
         :title="title"
         :isCloseConfirm="this.editable"
         :fullscreen="this.fullscreen"
         top="3%"
         width="80%"
         :close-on-click-modal="true"
         @modalOpened="opened"
         @modalClose="closed">

    <avue-form :option="option"
               ref="form"
               v-model="form"
               @submit="onSubmit">
      <template #supNo v-if="this.editable">
        <el-autocomplete
                style="width: 100%;"
                v-model="form.supNo"
                :fetch-suggestions="querySupplierNo"
                placeholder="请输入供应商账号"
                :trigger-on-focus="false"
                @select="selectSupplierNo"
                :fit-input-width="true"
                :disabled="!!this.form.id"
        ></el-autocomplete>
      </template>
      <template #supName v-if="this.editable">
        <el-input v-model="form.supName" readonly placeholder="请选择供应商名称" @click="selectSupplierName" :disabled="!!this.form.id"/>
      </template>
      <template #purchaseNoteItem>
        <purchase-note-item ref="purchaseNoteItem" :sendOrgId="this.form.sendOrgId">

        </purchase-note-item>
      </template>
    </avue-form>

    <!--底部按钮块, 默认只有"取消"按钮-->
    <template #footerButton>
      <el-button
              type="primary"
              v-if="(permission.purchase_note_main_add || permission.purchase_note_main_edit) && editable"
              :loading="btnLoading"
              @click="this.$refs.form.submit()"
      >保 存
      </el-button>
      <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
    </template>
    <select-supplier ref="selectSupplierRef" @success="setSupplier"></select-supplier>
  </modal>
</template>
<script>
    import {update,getDetail} from "@/api/anwise/purchase/purchase_note_main";
    import {ownerList,findSupplierByDeptId} from "@/api/anwise/supplier";
    import {userCompany} from "@/api/anwise/common";
    import {mapGetters} from "vuex";
    import {Pattern} from "@/utils/validate.js";
    import {dateFormat} from "@/utils/date.js";
    import purchaseNoteItem from './purchase_note_item.vue';
    import selectSupplier from './select_supplier.vue';

    export default {
        components: {
            purchaseNoteItem,
            selectSupplier
        },
        data() {
            return {
                emits: ["success"],
                supplierIdTmp:'',
                dept:{},
                supplierData:{},
                editable: false,
                title: "通知单信息",
                isCloseConfirm: false,
                fullscreen: false,
                form: {},
                query: {},
                loading: true,
                btnLoading: false,
                option: {
                    card: true,
                    tabs: true,
                    tabsActive: 1,
                    height: 'auto',
                    calcHeight: 30,
                    labelWidth: 150,
                    menuWidth: 120,
                    submitBtn: false,
                    emptyBtn: false,
                    column: [
                        {
                            label: "通知单编号",
                            prop: "idNo",
                            type: "input",
                            disabled:true,
                            span:8,
                            placeholder:'保存后自动生成单号',
                            rules: [{
                                required: false,
                                message: "请输入通知单编号",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "供应商编号",
                            prop: "supNo",
                            type: "number",
                            precision:0,
                            min:0,
                            max:999999999,
                            controls:false,
                            disabled:true,
                            span:8,
                            rules: [{
                                required: true,
                                message: "请输入供应商账号",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "供应商名称",
                            prop: "supName",
                            type: "input",
                            disabled:true,
                            span:8,
                            rules: [{
                                required: true,
                                message: "请输入供应商名称",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "发送单位",
                            prop: "sendOrg",
                            type: "input",
                            disabled:true,
                            span:8,
                            rules: [{
                                required: true,
                                message: "请输入发送单位",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "送货地址",
                            prop: "ccTo",
                            type: "input",
                            span:8,
                            rules: [{
                                required: false,
                                message: "请输入送货地址",
                                trigger: "blur"
                            }],
                        },
                        {
                            label: "送货日期",
                            prop: "deliDate",
                            type: "date",
                            valueFormat: 'YYYY-MM-DD',
                            format:'YYYY-MM-DD',
                            span:8,
                            rules: [{
                                required: true,
                                message: "请选择送货日期",
                                trigger: "blur"
                            }],
                        },
                    ],
                    group: [
                        {
                            icon: 'el-icon-house',
                            label: '通知项信息',
                            prop: 'group1',
                            column: [
                                {
                                    label: '',
                                    prop: 'purchaseNoteItem',
                                    className: 'addPadding',
                                    span: 24,
                                    labelWidth: 0,
                                    formslot: true,
                                    display: true,
                                },
                            ],
                        },
                    ]
                },
                data: []
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.validData(this.permission.purchase_note_main_add, false),
                    viewBtn: this.validData(this.permission.purchase_note_main_view, false),
                    delBtn: this.validData(this.permission.purchase_note_main_delete, false),
                    editBtn: this.validData(this.permission.purchase_note_main_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        mounted() {
          // this.init()
            findSupplierByDeptId().then(res => {
                if (res.data.success) {
                    this.supplierData = res.data.data;
                    if (!this.supplierData) {
                        this.$message({
                            type: "error",
                            message: "用户无组织机构信息，请联系安伟工作人员！"
                        });
                        return;
                    } else {
                        const ccTo = this.findObject(this.option.column, 'ccTo');
                        ccTo.value = this.supplierData.supAddr;
                        // this.form.ccTo = this.supplierData.supAddr;
                    }
                }
            })
        },
        methods: {
            // init() {
            //   this.form.tabDate = dateFormat(new Date(),'yyyy-MM-dd');
            // },
            selectSupplierName() {
                // if (this.supplierIdTmp) {
                //     this.$confirm("确定将选择数据删除?", {
                //         confirmButtonText: "确定",
                //         cancelButtonText: "取消",
                //         type: "warning"
                //     })
                //         .then(() => {
                //
                //         })
                // }
              this.$refs.selectSupplierRef.showSelect("采购商",this.form.sendOrgId);
            },
            setSupplier(row) {
                this.form.supId = row.supId;
                this.$refs.purchaseNoteItem.deptId = row.deptId;
                this.form.deptId = row.deptId;
                this.form.supNo = row.supNo;
                this.form.supName = row.supName;
            },
            querySupplierNo(val,cb) {
                const reg = Pattern.number;
              this.form.supName = "";
                console.log(reg.test(val));
                if (!reg.test(val)) {
                    this.$message({
                        type: "error",
                        message: "供应商账号只能为数字!"
                    });
                    return;
                }

                ownerList(val,2,this.form.sendOrgId).then(res => {
                    if (res.data.success) {
                        let customerList = [];
                        res.data.data.forEach(item => {
                            customerList.push({
                                value:item.supNo +" - "+item.supName,
                                supId: item.id,
                                deptId: item.deptId,
                                supNo: item.supNo,
                                supName: item.supName,
                            });
                        })
                        cb(customerList);
                    }
                })
            },
            selectSupplierNo(item) {
                console.log(item);
                this.form.supId = item.supId;
                this.$refs.purchaseNoteItem.deptId = item.deptId;
                this.form.deptId = item.deptId;
                this.form.supNo = item.supNo;
                this.form.supName = item.supName;
            },
            async validItemEvent() {
                const $table = this.$refs.purchaseNoteItem.$refs.tableRef
                let errMap = undefined;
                await $table.validate().then((err) => {
                    console.log("err",err);
                    errMap=err;
                })
                return errMap;
            },
            async onSubmit(form, done) {
                const $table = this.$refs.purchaseNoteItem.$refs.tableRef
                let checkprodItem = false;
                const errMap = await this.validItemEvent();

                if (errMap) {
                    this.$message({
                        type: 'error',
                        message: '通知项信息有误！',
                    });
                    checkprodItem = true;
                    done();
                    return;
                }

                console.log("checkprodItem",checkprodItem);
                if (!checkprodItem) {
                    this.btnLoading = true;
                    form.addList = this.$refs.purchaseNoteItem.$refs.tableRef.getInsertRecords();
                    form.updateList = this.$refs.purchaseNoteItem.$refs.tableRef.getUpdateRecords();
                    form.deleteList = this.$refs.purchaseNoteItem.$refs.tableRef.getRemoveRecords();
                    const itemList = this.$refs.purchaseNoteItem.$refs.tableRef.getTableData().fullData;
                    if (!itemList || itemList.length < 1) {
                        this.$message({
                            type: 'error',
                            message: '无通知项信息！',
                        });
                        this.btnLoading = false;
                        done();
                        return;
                    }
                    console.log(form)
                    update(form).then(res => {
                        if (res.data.success) {
                            this.$message({
                                type: "success",
                                message: res.msg || "保存成功!"
                            });
                            setTimeout(() => {
                              this.btnLoading = false;
                              done();
                                this.$refs.modal_1.hide();
                            }, 1000)
                        } else {
                            this.$message({
                                type: "error",
                                message: res.msg || "保存失败!"
                            });
                        }
                    }).catch(err => {
                        console.log(err)
                        done();
                        this.btnLoading = false;
                    })

                }
            },
            show(option) {
                if (option.id) {
                    this.findObject(this.option.column, 'supNo').disabled = true;
                    this.findObject(this.option.column, 'supName').disabled = true;
                    setTimeout(() => {
                        getDetail(option.id).then(res =>{
                            if (res.data.success) {
                                this.form = res.data.data;
                                this.$refs.purchaseNoteItem.setData(this.editable, this.form.idNo,this.form.deptId)
                            }
                        })
                    }, 500);
                } else {
                    this.form={}
                    this.form.tabDate = dateFormat(new Date(),"yyyy-MM-dd")
                    userCompany().then(res => {
                        if (res.data.success) {
                            this.dept = res.data.data;
                            if (!this.dept) {
                                this.$message({
                                    type: "error",
                                    message: "用户无组织机构信息，请联系安伟工作人员！"
                                });
                                return;
                            }
                                this.form.sendOrg = this.dept.deptName;
                                this.form.sendOrgId = this.dept.id;

                        }
                    })

                }
                this.title = option.title;
                this.type = option.type;
                this.option.detail = this.type === "view";
                this.editable = this.type !== "view";
                // this.findObject(this.option.column, 'purchaseType').change = function ({column,value}){this.changePurchaseType()};
                this.$refs.modal_1.show();
            },
            changePurchaseType(value) {
                // this.$confirm("切换类型会丢失现有数据，确定继续吗?", {
                //     confirmButtonText: "确定",
                //     cancelButtonText: "取消",
                //     type: "warning"
                // })
                //     .then(() => {
                        this.$refs.purchaseNoteItem.changePurchaseType(value);
                    // });
            },
            rowSave(row, done, loading) {
                add(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowUpdate(row, index, done, loading) {
                update(row).then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    done();
                }, error => {
                    loading();
                    window.console.log(error);
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                    });
            },
            handleDelete() {
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(this.ids);
                    })
                    .then(() => {
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$refs.crud.toggleSelection();
                    });
            },
            beforeOpen(done, type) {
                if (["edit", "view"].includes(type)) {
                    getDetail(this.form.id).then(res => {
                        this.form = res.data.data;
                    });
                }
                done();
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1
                this.onLoad(this.page, params);
                done();
            },
            selectionChange(list) {
                this.selectionList = list;
            },
            selectionClear() {
                this.selectionList = [];
                this.$refs.crud.toggleSelection();
            },
            currentChange(currentPage){
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad(this.page, this.query);
            },
            onLoad(page, params = {}) {
                this.loading = true;
                getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    const data = res.data.data;
                    this.page.total = data.total;
                    this.data = data.records;
                    this.loading = false;
                    this.selectionClear();
                });
            },
            opened() {
                console.log("opened")
            },
            closed() {
                this.$emit("success");
            }
        }
    };
</script>

<style>
</style>
